package com.juyu.miliao.common.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @author jh
 * 2018/10/7
 */
public class OkHttpUtil {

    private static final OkHttpClient DEFAULT_CLIENT = new OkHttpClient();

    public static Response getSyn(OkHttpClient okHttpClient, String url, Map<String, Object> parms) {

        if (StringUtils.isEmpty(url)) {
            return null;
        }

        if (okHttpClient == null) {
            okHttpClient = DEFAULT_CLIENT;
        }

        Request request = new Request.Builder()
                .url(url + combineGetParms(parms))
                .build();

        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;
    }


    public static String combineGetParms(Map<String, Object> parms) {
        if (parms != null && !parms.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> entry : parms.entrySet()) {
                String key = entry.getKey();
                checkedParms(key);
                Object valueObj = entry.getValue();
                checkedParms(valueObj);
                sb.append("&").append(key).append("=").append(valueObj.toString());
            }
            if (sb.length() > 0) {
                sb.replace(0, 1, "?");
            }
            return sb.toString();
        }
        return "";
    }

    public static void checkedParms(Object object) {
        if (object == null || "".equals(object.toString())) {
            throw new RuntimeException("parms参数异常");
        }
    }


}
